package com.caiyi.financial.nirvana.sms.gateway.cmpp.cmpp20;

import com.alibaba.fastjson.JSON;
import com.caiyi.financial.nirvana.sms.gateway.KeepConnectGateWay;
import com.caiyi.financial.nirvana.sms.gateway.cmpp.CMPPHeader;
import com.caiyi.financial.nirvana.sms.gateway.cmpp.CMPPMessageTool;
import com.caiyi.financial.nirvana.sms.gateway.cmpp.CharsetInfo;
import com.caiyi.financial.nirvana.sms.gateway.cmpp.LongMsgHeader;
import com.caiyi.financial.nirvana.sms.gateway.cmpp.cmpp20.message.CMPPMessage;
import com.caiyi.financial.nirvana.sms.gateway.cmpp.cmpp20.message.body.CMPPSubmit;
import com.caiyi.financial.nirvana.sms.queue.SendQueueEntity;
import com.caiyi.financial.nirvana.sms.util.CommUtil;
import com.caiyi.financial.nirvana.sms.util.Constant;
import com.caiyi.financial.nirvana.sms.util.HttpClientUtil;
import io.netty.channel.ChannelFutureListener;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * CMPP客户端入口类
 *
 * @author lvchaohua
 */
public class CMPPClient extends KeepConnectGateWay {

    //记录cmpp协议发送消息
    private static final Logger logger = LogManager.getLogger(CMPPClient.class);

    /**
     * 客户端构造函数
     *
     * @throws InterruptedException
     */
    public CMPPClient() {
        super();
    }

    //开启CMPP客户端
    public void start() throws InterruptedException {
        super.start();
        bootstrap.handler(new CMPPClientInitializer(this));
    }

    //发送短信
    @Override
    public void sendMessage(SendQueueEntity entity) {
        String json = JSON.toJSONString(entity);
        try {
            logger.info("CMPPClient send : {}", json);
            String[] phoneArr = entity.getPhone().split(",");
            String[] messageIdArr = entity.getMessageId().split(",");
            for (int i = 0; i < phoneArr.length; i++) {
                String messageId = messageIdArr[i];
                CMPPSubmit submit = new CMPPSubmit();
                submit.setLevel((byte) 10);
                submit.setMessageFormat(CharsetInfo.UCS2);
                submit.setSpId(entity.getAccount());
                submit.setServiceId("");
                submit.setSrcId(entity.getAccessNumber());
                submit.setDestTerminalId(new String[]{phoneArr[i]});
                submit.setMessageContent(entity.getContent());
                CMPPMessage message = new CMPPMessage();
                CMPPHeader header = new CMPPHeader();
                header.setCommandID(CMPPMessage.CMPP_SUBMIT);
                message.setHeader(header);
                // 长短信内容分割
                List<String> contentChips = CommUtil.splitLongContent(entity.getContent());
                int sendNum = contentChips.size() > 1 ? contentChips.size() : 1;
                // 长短信设置
                if (sendNum > 1) {
                    byte total = (byte) sendNum;
                    byte serial = CMPPMessageTool.getOne();
                    for (int index = 0; index < contentChips.size(); index++) {
                        CMPPMessage message2 = (CMPPMessage) message.clone();
                        CMPPSubmit submit2 = (CMPPSubmit) submit.clone();
                        LongMsgHeader msgHeader = new LongMsgHeader();
                        // 设置sequenceId对应的发送信息
                        int sequenceId = Constant.seqNo.incrementAndGet();
                        S2M.put(String.valueOf(sequenceId), messageIdArr[i]);
                        message2.setSequenceId(sequenceId);
                        msgHeader.setSerial(serial);
                        msgHeader.setTotal(total);
                        msgHeader.setNumber((byte) (index + 1));
                        String contentChip = contentChips.get(index);
                        submit2.setMessageContent(contentChip);
                        submit2.setMsgHeader(msgHeader);
                        submit2.setTpUdhi((byte) 1);
                        submit2.setPkTotal(total);
                        submit2.setPkNumber((byte) (index + 1));
                        message2.setBody(submit2);
                        context.writeAndFlush(message2).addListener((future) -> logger.info("CMPPClient phone : {}, isDone : {}, isSuccess : {}", entity.getPhone(), future.isDone(), future.isSuccess())).addListener(ChannelFutureListener.CLOSE_ON_FAILURE);
                    }
                } else {
                    // 设置sequenceId对应的发送信息
                    int sequenceId = Constant.seqNo.incrementAndGet();
                    S2M.put(String.valueOf(sequenceId), messageIdArr[i]);
                    message.setSequenceId(sequenceId);
                    message.setBody(submit);
                    context.writeAndFlush(message).addListener((future) -> logger.info("CMPPClient phone : {}, messageId : {}, isDone : {}, isSuccess : {}, sequenceId : {}", entity.getPhone(), messageId, future.isDone(), future.isSuccess(), sequenceId)).addListener(ChannelFutureListener.CLOSE_ON_FAILURE);
                }
            }
        } catch (Exception e) {
            logger.error("CMPPClient sendMessage error message : {}", json);
        }
    }

    @Override
    public int queryBalance() throws Exception {
        int balance = 0;
        //查询大汉三通余额
        if (info.getId() == 25 || info.getId() == 26) {
            String url = "http://www.dh3t.com/json/sms/Balance";
            Map params = new HashMap();
            params.put("account", "410593");
            params.put("password", "i3rbxN7V");
            String json = HttpClientUtil.doPost(url, JSON.toJSONString(params));
            Map result = JSON.parseObject(json, Map.class);
            String code = result.get("result").toString();
            if ("0".equals(code)) {
                Map m = (Map) result.get("smsBalance");
                balance = Integer.parseInt(m.get("number").toString());
            }
        }
        return balance;
    }

}